package cn.edu.ctbu.finaltest.controller;



import cn.edu.ctbu.finaltest.core.PageUtils;
import cn.edu.ctbu.finaltest.domain.SelectCourse;
import cn.edu.ctbu.finaltest.domain.Teacher;
import cn.edu.ctbu.finaltest.exception.REnum;
import cn.edu.ctbu.finaltest.exception.RException;
import cn.edu.ctbu.finaltest.service.CourseService.CourseService;
import cn.edu.ctbu.finaltest.service.SelectCourseService.SelectCourseService;
import cn.edu.ctbu.finaltest.service.StudentService.StudentService;
import cn.edu.ctbu.finaltest.service.TeacherCourseService.TeacherCourseService;
import cn.edu.ctbu.finaltest.service.TeacherTeachingService.TeacherTeachingService;
import cn.edu.ctbu.finaltest.vo.R;
import cn.edu.ctbu.finaltest.vo.TeacherTeaching;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class TeacherController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private SelectCourseService selectCourseService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private TeacherCourseService teacherCourseService;
    @Autowired
    private TeacherTeachingService teacherTeachingService;

    @RequestMapping("/teacher/teacherList.html")
    public String studentListDisplay(){return "teacher/teacherList";}
    @RequestMapping("/teacher/loginScreen.html")
    public String administratorLoginScreen(){return "login/loginScreen";}

    @ResponseBody
    @RequestMapping("/teacher/showName")
    public String teacherName(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("2") || session.getAttribute("userid") == null){
            throw new RException(REnum.LOGIN_ERR);
        }
        Teacher teacherMessage = (Teacher) session.getAttribute("user");
        return teacherMessage.getTname();
    }

    @ResponseBody
    @RequestMapping("/teacher/displayList")
    public PageUtils teacherGetByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
                                      @RequestParam(value = "size",defaultValue = "10") Integer size,
                                      @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                      HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("2") || session.getAttribute("userid") == null){
            throw new RException(REnum.LOGIN_ERR);
        }
        Teacher teacherMessage = (Teacher) session.getAttribute("user");

        List<SelectCourse> studentSelectCourse = selectCourseService.findAll();
        List<TeacherTeaching> teacherTeachings = new ArrayList<>();
        int count = 0;
        //序号，课号，课名，学分，课时，学号，姓名，分数
        for (int i = 0;i < studentSelectCourse.size();i++){
            if (teacherCourseService.findByCno(studentSelectCourse.get(i).getCno()).size() != 0 && teacherCourseService.findByCno(studentSelectCourse.get(i).getCno()).get(0).getTno().equals(teacherMessage.getTno())){
                TeacherTeaching teacherTeaching = new TeacherTeaching();
                teacherTeaching.setId(++count);
                teacherTeaching.setScore(studentSelectCourse.get(i).getScore());
                teacherTeaching.setCno(studentSelectCourse.get(i).getCno());
                teacherTeaching.setSno(studentSelectCourse.get(i).getSno());
                teacherTeaching.setCname(courseService.findByCno(studentSelectCourse.get(i).getCno()).getCname());
                teacherTeaching.setSname(studentService.findBySno(studentSelectCourse.get(i).getSno()).getSname());
                teacherTeaching.setCredit(courseService.findByCno(studentSelectCourse.get(i).getCno()).getCredit());
                teacherTeaching.setScore(studentSelectCourse.get(i).getScore());
                teacherTeaching.setHour(courseService.findByCno(studentSelectCourse.get(i).getCno()).getHour());
                teacherTeachings.add(teacherTeaching);
            }
        }
        //设置分页
        int teacherTeachingsSize = teacherTeachings.size();
        teacherTeachings = teacherTeachings.stream().skip((pageNum-1)*size).limit(size).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(teacherTeachings,teacherTeachingsSize);

        return pageUtils;

    }

    @ResponseBody
    @RequestMapping("/teacher/teacherEdit/{snoAndCno}")
    public TeacherTeaching get(@PathVariable String snoAndCno,HttpServletRequest httpServletRequest){
        List<TeacherTeaching> teacherTeachings = (List<TeacherTeaching>) teacherGetByPage(0, 2000000000, 1, httpServletRequest).getRows();
        String[] arrayList = snoAndCno.split("!");

        String sno = arrayList[0];
        String cno = arrayList[1];


        TeacherTeaching teacherTeaching = new TeacherTeaching();
        for (int i = 0;i < teacherTeachings.size();i++){
            if (cno.equals(teacherTeachings.get(i).getCno()) && sno.equals(teacherTeachings.get(i).getSno())){
                teacherTeaching = teacherTeachings.get(i);
            }
        }

        return teacherTeaching;
    }

    @ResponseBody
    @RequestMapping("/teacher/saveScore/{data}")
    public void saveScore(@PathVariable String data){
        String[] arrayList = data.split("!");
        String sno = arrayList[0];
        String cno = arrayList[1];
        String score = arrayList[2];
        List<SelectCourse> selectCourses = selectCourseService.findByCnoAndSno(cno,sno);
        SelectCourse selectCourse = selectCourses.get(0);
        selectCourse.setScore(Float.parseFloat(score));
        selectCourseService.update(selectCourse);
    }

    @ResponseBody
    @RequestMapping("/teacher/search")
    public PageUtils studentSearch(@RequestParam(value = "size",defaultValue = "10") Integer size,
                                   @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                   @RequestParam(value = "name",defaultValue = "") String name,
                                   HttpServletRequest httpServletRequest) throws Exception {

        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("2") || session.getAttribute("userid") == null){
            throw new RException(REnum.LOGIN_ERR);
        }
        String[] arrayList = name.split("!");

        name = arrayList[0];
        String searchOption = arrayList[1];
        String searchMatching = arrayList[2];

        R<List<TeacherTeaching>> RTeacherTeachings = new R<>();

        PageUtils allTeacherList = teacherGetByPage(0, 2000000000, 1, httpServletRequest);


        if (searchMatching.equals("20")) {//模糊查询
            if (searchOption.equals("10")) {//课号查询
                RTeacherTeachings = teacherTeachingService.findByCnoLike(name, (List<TeacherTeaching>) allTeacherList.getRows());
            } else if (searchOption.equals("11")) {//以课程名查询
                RTeacherTeachings = teacherTeachingService.findByCnameLike(name, (List<TeacherTeaching>) allTeacherList.getRows());
            } else if (searchOption.equals("12")) {//以学号名查询
                RTeacherTeachings = teacherTeachingService.findBySnoLike(name, (List<TeacherTeaching>) allTeacherList.getRows());
            } else  {//以学生名查询
                RTeacherTeachings = teacherTeachingService.findBySnameLike(name, (List<TeacherTeaching>) allTeacherList.getRows());
            }
        } else {//精确查询
            if (searchOption.equals("10")) {//课号查询
                RTeacherTeachings = teacherTeachingService.findByCno(name, (List<TeacherTeaching>) allTeacherList.getRows());
            } else if (searchOption.equals("11")) {//以课程名查询
                RTeacherTeachings = teacherTeachingService.findByCname(name, (List<TeacherTeaching>) allTeacherList.getRows());
            }  else if (searchOption.equals("12")) {//以学号名查询
                RTeacherTeachings = teacherTeachingService.findBySno(name, (List<TeacherTeaching>) allTeacherList.getRows());
            } else  {//以学生名查询
                RTeacherTeachings = teacherTeachingService.findBySname(name, (List<TeacherTeaching>) allTeacherList.getRows());
            }
        }
        int RTeacherTeachingsSize = RTeacherTeachings.getData().size();
        RTeacherTeachings.setData(RTeacherTeachings.getData().stream().skip((pageNum - 1) * size).limit(size).collect(Collectors.toList()));
        PageUtils pageUtils = new PageUtils(RTeacherTeachings.getData(), RTeacherTeachingsSize);

        return pageUtils;
    }
}
